<template>
  <el-cascader
    :class="{ 'cascader-input': placeholderFlag }"
    :props="props"
    @change="changeValue"
    :placeholder="placeholderValue"
  ></el-cascader>
</template>

<script>
import { GetCity } from "@/request/common";
export default {
  props: {
    cityAreaValue: {
      type: String,
      default: "",
    },
  },
  data() {
    const _this = this;
    return {
      address: [],
      addressData: [],
      props: {
        lazy: true,
        async lazyLoad(node, resolve) {
          // 请求参数
          const { level } = node;
          const requestData = {};
          const jsonType = {
            0: { type: "province" },
            1: { type: "city", code: "province" },
            2: { type: "area", code: "city" },
          };
          if (jsonType[level].code) {
            requestData[`${jsonType[level].code}_code`] = node.value;
          }
          requestData.type = jsonType[level].type;
          const type = jsonType[level].type.toUpperCase();
          const { data } = await GetCity(requestData);
          const dataList = data.data.data;
          _this.addressData[jsonType[level].type] = dataList;
          if (dataList) {
            dataList.forEach((item, index) => {
              item.value = item[`${type}_CODE`];
              item.label = item[`${type}_NAME`];
              if (level === 2) {
                item.leaf = level >= 2;
              }
            });
          }
          resolve(dataList);
          if (level > 0) {
            _this.getAddress(node);
          }
        },
      },
      placeholderValue: "请选择省市区",
      placeholderFlag: false,
    };
  },
  methods: {
    changeValue(value) {
      this.$emit("update:cityAreaValue", value.join());
      const lastCode = value[value.length - 1];
      const area = this.addressData.area.filter(
        (item) => item.value === lastCode
      )[0];
      this.address[2] = area.label;
      this.getAddress();
    },
    getAddress(node) {
      if (node) {
        const index = node.level - 1;
        this.address[index] = node.label;
      }
      this.$emit("callback", {
        function: "setMapCenter",
        data: this.address.join(""),
      });
    },
    initDefault(value) {
      console.log(value);
      this.placeholderValue = value.split(",").join("/");
      this.placeholderFlag = true;
    },
  },
};
</script>